/* Copyright (c) 2009 Byron Adams <byron.adams54@gmail.com>
   See the file LICENSE for licensing information. */

translator.plugin("translate", {
  /**
   *  
   * @access public
   * @param object
   * @param object
   * @return bool
   */
  serviceFilter : function (filter, service) {
    if (("translate" in service) && ("langSets" in service)) {
      if (("srcLang" in filter) && (filter.srcLang in service.langSets))
        if (("destLang" in filter)) return service.langSets[filter.srcLang].indexOf(filter.destLang) >= 0;
      else
        return true;
    }
    return false;
  },
  
  /**
   *  @access public
   */
  method : function (options) {
    
    if ("services" in options) options.services.shift();

    var srcLang = translator.getLanguage(options.srcLang);
    var destLang = translator.getLanguage(options.destLang);
    
    options.services = options.services || translator.getServices({
      type : "translate",
      srcLang : srcLang.name,
      destLang : destLang.name
    });
    
    if (options.services.length == 0) {
      return options.fail("No Services");
    }
    
    var s = options.services[0], charLimit = s.translate.charLimit || 128;
    var buffer = options.text, i = 0, chunks = [];
    
    while (buffer.length > 0) {
      var split = buffer.length < charLimit ? buffer.length : buffer.substring(0, charLimit).lastIndexOf(" ");
      if (split < 0) split = buffer.length;
      translateChunk(parseInt(i), buffer.substring(0, split));
      buffer = buffer.substring(split);
      i++;
    }
    
    function translateChunk(id, text) {
      chunks.push(false);
      s.translate.method({
        text : text,
        srcLang : s.langFilter[srcLang.name] || srcLang.code,
        destLang : s.langFilter[destLang.name] || destLang.code,
        success : function (data) {
          chunks[id] = data;
          if (!chunks.some(function (e) {return !e}) && buffer.length == 0) {
            options.success(chunks.join(" ") + " ");
          }
        },
        fail : function () {
          if (options.services.length > 1) translator.translate(options);
          else options.error.apply(options, arguments);
        }
      });
    }
    return true;
  }

});
